import datetime
import json
import pymysql
from flask import (Flask, request, render_template, g,
                   session, redirect, url_for, flash)
import requests
from conn_mysql import MysqlApi, ConnectMysql
from setting import *
from weixin_pay import app_weixin_pay
from sms import app_send_sms
from flask_cors import CORS
from sms import SendSms

app = Flask(__name__)
CORS(app)
app.register_blueprint(app_weixin_pay)
# app.register_blueprint(app_send_sms)
app.config["SECRET_KEY"] = "OWNVNHJOIoojdlkjfOIDFH"

##########过滤器注册 start ##########
@app.template_filter('phone_notify')
def time_filter(s):
    return s[0:3] + '****' + s[-4:]


@app.template_filter('time_filter')
def time_filter(s):
    return s.__str__()[5:10]

@app.template_filter('company_id_to_name')
def compan_id_to_name(company_id):

    with MysqlApi() as m:
        result = m.select_company_for_openid(company_id=company_id)
    return result['company_name']

@app.template_filter('company_id_to_phone')
def compan_id_to_phone(company_id):

    with MysqlApi() as m:
        result = m.select_company_for_openid(company_id=company_id)
    return result['phone']

@app.template_filter('company_id_to_linkman')
def compan_id_to_linkman(company_id):

    with MysqlApi() as m:
        result = m.select_company_for_openid(company_id=company_id)
    return result['linkman']

@app.template_filter('need_id_to_need')
def need_id_to_need(need_id):

    with MysqlApi() as m:
        sql = "SELECT * FROM need where id=%s"
        result = m.select_one(sql, need_id)
    return result['need']
@app.template_filter('need_id_to_company_id')
def need_id_to_company_id(need_id):

    with MysqlApi() as m:
        sql = "SELECT * FROM need where id=%s"
        result = m.select_one(sql, need_id)
    return result['company_id']




##########过滤器注册 end #############

@app.route('/openid_callback')#获取用户openID
def openid_callback():


    data = request.args
    code = data['code'] if 'code' in data else None
    if not code:
        return redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx90014a2b7a9ab7f2&redirect_uri=http%3A//www.gogok12.com/openid_callback&response_type=code&scope=snsapi_base&connect_redirect=1#wechat_redirect")

    # 你的appid,appsecret
    app_id ,app_key = APPID, APPKEY
    
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + app_id + '&secret=' + app_key + '&code=' + code + '&grant_type=authorization_code'
    r = requests.get(url)
    res = json.loads(r.text)
    openid = res["openid"]
    
    with MysqlApi() as m:
        openid_state = m.company_status(openid)#检测openid对应的情况

    session['company_state'] = openid_state['company_state']
    session['company_update_state'] = openid_state['company_update_state']
    session['company_id'] = openid_state['company_id']
    session['openid'] = openid
    return redirect(url_for("index"))

@app.route('/')#首页
def index():

    openid = session.get('openid')
    # 本地测试
    # openid = '002'
    # session['company_state'] = 0
    # session['company_update_state'] = 0
    # session['openid'] = openid
    # session['company_id'] = 63
    
    # if request.args.get('msg') == '付费成功':
    #     flash('恭喜您成为本站会员', 'alert-success')
    if openid == None:
        return redirect(url_for("openid_callback"))

    page = request.args.get('page')
    limit = request.args.get('limit')
    party = request.args.get('party')

    with MysqlApi() as m:

        result = m.select_need_all(page, limit, party)

    if page == None or page == '1':
        pre_page = 1
        next_page = 2

    else:
        pre_page = int(page) - 1
        next_page = int(page) + 1

    
    return render_template("index.html", info=result, 
                            party=party, pre_page=pre_page, 
                            next_page=next_page)

@app.route('/detail/<int:ID>')#详情
def detail(ID):
    session['last_id'] = ID
    openid = session.get("openid")
    company_id = session.get('company_id')
    if not openid: 
        flash('你在微信环境下浏览首页', 'alert-success')
        return redirect(url_for("index"))
    
    company_state = session['company_state']
    company_update_state = session['company_update_state']
    company_id = session.get('company_id')

    with MysqlApi() as m:

        result_info = m.select_need(ID)

        result_info.update({"regedate": result_info['regedate'] + datetime.timedelta(hours=8)})

        result_pay = m.select_need_pay(ID, company_id)
    

    return render_template(
        "detail.html", 
        result_info=result_info, 
        result_pay=result_pay,
        company_update_state = company_update_state,
        company_state = company_state,
        )


@app.route('/post_phone')#验证手机页面
def post_phone():

    return render_template("post_phone.html")

@app.route("/sms_phone")
def sms_phone():

    

    phone = session['phone']
    # phone = '13833333333'
    

    return render_template("sms_phone.html", phone=phone)
@app.route('/post_phone_', methods = ["POST"])#验证手机程序 
def post_phone_():

    phone = request.form.get("phone")
    #判断手机合法性并发送短信
    with ConnectMysql() as c:

        sql = "SELECT * FROM company WHERE phone=%s"

        if c.select_one(sql, (phone,)):
            flash("您的手机号码已经注册过了！！", 'alert-danger')
            return redirect(url_for("post_phone"))

    send_obj = SendSms(phone)
    send_msg = send_obj.send_info#发送短信验证码

    if send_msg["Message"] == "OK":

        #插入code到数据库存中
        with ConnectMysql() as c:

            sql = "INSERT INTO notify_code(notify_code, phone) values (%s,%s)"

            c.insert_info(sql, (send_obj.code, phone))

        session['phone'] = phone

        flash("短信验证码已经发送！！", 'alert-success')

        return render_template("sms_phone.html", phone = phone)

    else:

        flash("验证码发送失败！！", 'alert-danger')
        return redirect(url_for("post_phone"))
        
@app.route('/notify_code', methods = ['POST'])
def notify_code():

    openid = session.get("openid")
    phone = session.get("phone")
    notify_code = request.form.get('notify_code')
    print(notify_code)
    #如果提交来的验证码不为空则判断-->start
    if notify_code:
        #验证手机验证码是否有效-->start
        with ConnectMysql() as c:

            sql = "SELECT * FROM notify_code WHERE notify_code=%s and phone=%s"

            notify_result = c.select_one(sql, (notify_code, phone))

        if not notify_result:
            
            flash("手机验证码不正确,请重新输入", 'alert-danger')
            return redirect('/sms_phone')
            
        if notify_result['regedate'] + datetime.timedelta(hours=8, minutes=15) < datetime.datetime.now():
            flash("手机验证码已经失效", 'alert-danger')
            return redirect(url_for("post_phone"))
        else:
            flash("手机验证通过！！", 'alert-success')
            return redirect(url_for("register"))
        #验证手机验证码是否有效-->end
    #如果提交来的验证码不为空则判断--->end


@app.route('/register', methods = ["GET"])#注册表格页面
def register():

    openid = session.get("openid")

    if openid == None:

        flash('微信环境下浏览本页', 'alert-success')

        return redirect(url_for("index"))


    return render_template("register.html", openid=openid)


@app.route('/register_', methods = ["POST"])#注册数据处理页面
def register_():

    openid = session.get("openid")

    if openid == None:
        flash('微信环境下浏览本页', 'alert-success')
        return redirect(url_for("index"))

    info = request.form
    free_id = session.get("last_id")#注册时可以免费看一个电话
    phone = session.get('phone')

    if not phone:

        flash("请验证手机号码再进行注册！！", 'alert-danger')
        return redirect(url_for("post_phone"))

        
    #注册信息入库-->start
    data = dict(  
        company_id = session['company_id'],
        company_name = info.get('company_name'),
        linkman = info.get('linkman'),
        phone = phone,
        need = info.get('need'),
        party = info.get('party'),
        openid = openid
    )


    with MysqlApi() as m:

        m.register(**data)
        m.insert_pay_log(session['company_id'], free_id, pay_status=1)

    session['company_state'] = 1#改变company_state为注册状态
    flash('欢迎加入！温馨提示-请妥善保存本页的电话码！', 'alert-success')
    return redirect(f'/detail/{free_id}')
    

@app.route('/publish')#发布页面渲染
def publish():

    openid = session.get("openid")
    if not openid: 
        flash('你在微信环境下浏览首页', 'alert-success')
        return redirect(url_for("index"))

    if not session['company_state']:

        flash('你还未注册，请注册后发布', 'alert-danger')
        return redirect(url_for("post_phone"))


    with MysqlApi() as m:

        company_info = m.select_company_for_openid(company_id = session['company_id'])

    return render_template("publish.html", info=company_info)

@app.route('/publish_', methods=["POST"])#发布信息处理
def publish_():

    openid = session['openid']
    if not openid:
        # flash('', 'alert-danger')
        return redirect(url_for("index"))
        

    need = request.form.get('need')
    party = request.form.get('party')

    company_update_state = session['company_update_state']

    if company_update_state == 0:

        flash('每天只能发布一次', 'alert-danger')
        return redirect(url_for("publish"))


    with MysqlApi() as m:
        m.update_need(session['company_id'], need, party)
    flash('发布成功，每天只能发布一次', 'alert-success')
    return redirect(url_for("publish"))

@app.route('/coop')
def coop():

    return render_template("coop.html")


@app.route('/personal')
def person():
    company_id = session.get('company_id')
    if not company_id:

        flash('获取权限成功', 'alert-success')
        return redirect(url_for("index"))

    with MysqlApi() as m:
        
        result = m.select_need_pay_all(company_id)

    return render_template("personal.html", follow_info = result)


    

















if __name__ == '__main__':
    app.run(debug=True)
    